const app = getApp();
var dataFormat = require('../../utils/dataFormat.js');
Page({
  onShow() {
    wx.hideTabBar();
  },
  // 加载的时候设置tab类型 拿到桥梁列表
  onLoad: function() {

    // 初始化自定义Tabbar
    app.editTabbar();
    var that = this;
    that.setData({
      categories: [{
        id: 0,
        name: "我的桥梁"
      }, {
        id: 1,
        name: "其他桥梁"
      }],
      activeCategoryId: 0,
      token: wx.getStorageSync('openId')
    });

    that.getMyBridges();
    that.getOtherBridges();
  },
  // 获取设备高度
  getDeviceWidth: function() {
    wx.getSystemInfo({
      success: res => {
        //导航高度
        this.setData({
          navHeight: res.statusBarHeight + 46
        })
      },
      fail(err) {}
    })
  },

  // 获取桥梁数据
  getMyBridges: function() {
    var that = this;
    wx.request({
      url: app.globalData.siteUrl + '/bridge/queryBridgeList',
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Token": that.data.token,
      },
      data: {},
      success: function(res) {
        let myBridges = [];
        if (res.data.model) {
          for (var i = 0; i < res.data.model.length; i++) {
            let asta = res.data.model[i].status;
            let stat = '';
            stat = ((asta == 0) ? '待提交' : (asta == 1 ? '审核通过' : ((asta == 2 ? '审核不通过' : '待审核'))));
            res.data.model[i].status = stat;
            var newDate = new Date();
            var timestamp = res.data.model[i].createTime;
            let a = dataFormat.tsFormatTime(timestamp, 'Y/M/D');
            res.data.model[i].createTime = a;
            myBridges.push(res.data.model[i]);
          }
        }

        that.setData({
          myBridges: myBridges,
        });
        wx.setStorageSync('myBridges', myBridges);
      }
    });
  },

  // 获取其他桥梁数据
  getOtherBridges: function() {
    var that = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: app.globalData.siteUrl + '/bridge/queryOtherBridgeList',
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Token": that.data.token,
      },
      data: {},
      success: function(res) {
        var otherBridges = [];
        if (res.data.model != null) {
          for (var i = 0; i < res.data.model.length; i++) {
            var newDate = new Date();
            var timestamp = res.data.model[i].createTime;
            let a = dataFormat.tsFormatTime(timestamp, 'Y/M/D');
            res.data.model[i].createTime = a;
            otherBridges.push(res.data.model[i]);
          }
        }
        that.setData({
          otherBridges: otherBridges,
        });
        wx.setStorageSync("otherBridges", otherBridges);
      },
      complete: function() {
        wx.hideLoading();
      }
    });
  },
  // 点击tab 切换
  tabClick: function(e) {
    this.setData({
      activeCategoryId: e.currentTarget.id,
    });
  },
  search: function(e) {
    wx.navigateTo({
      url: '/pages/search/search'
    });
  },
  //  功能按钮被点击 action-sheet弹出
  actionSheetTap: function(e) {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden,
      id: e.currentTarget.dataset.id
    })
  },
  // action-sheet 点击取消按钮 action-sheet模块消失
  actionSheetChange: function(e) {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    });
  },
  actionSheet: function(e) {
    var item = e.currentTarget.dataset.item;
    if (item == '删除') {
      this.delItem();
    } else if (item == '提交审核') {
      this.submitShenhe();
    }
  },
  // 数据
  data: {
    actionSheetHidden: true,
    actionSheetItems: ['删除', '提交审核'],
    tabbar: {},
    openId: app.globalData.openId,
    delBtnWidth: 180, //删除按钮宽度单位（rpx)
    search_name: null,
    search_id: null,
    activeCategoryId: 0,
    myBridges: [],
    otherBridges: [],
  },

  // 提交审核申请
  submitShenhe: function(e) {
    var id = this.data.id;
    var that = this;
    wx.showModal({
      title: '确认提交审核',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.siteUrl + '/bridge/submit',
            method: 'post',
            header: {
              "X-Token": wx.getStorageSync("openId"),
              "Content-Type": "application/x-www-form-urlencoded",
            },
            data: {
              id: id,
              status: 4,
              extfeild: ''
            },
            success: function(res) {
              that.setData({
                actionSheetHidden: !that.data.actionSheetHidden
              });
            }
          });
          that.onLoad();
        } else if (res.cancel) {}
      }
    })
  },

  //点击删除按钮事件
  delItem: function() {

    var that = this;
    //获取列表中要删除项的下标
    var id = this.data.id;
    var that = this;
    //移除列表中下标为index的项
    wx.showModal({
      title: '提示',
      content: '确认删除',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.siteUrl + '/bridge/delete',
            method: 'post',
            header: {
              "Content-Type": "application/x-www-form-urlencoded",
              "X-Token": that.data.token,
            },
            data: {
              id: id
            },
            success: function(res) {
              wx.showToast({
                title: '成功',
                icon: 'success',
                duration: 2000
              });
              that.getMyBridges();
              that.setData({
                actionSheetHidden: !that.data.actionSheetHidden
              });
            }
          });
        } else if (res.cancel) {}
      }
    })

  },

  // 跳转到详细信息页面
  kindToggle: function(e) {
    let activeCategoryId = this.data.activeCategoryId;
    var bridgeId = e.currentTarget.dataset.id;

    let bridges = activeCategoryId == 0 ? this.data.myBridges : this.data.otherBridges;
    let bridgeInfo = bridges.find(function(bridge) {
      return bridge.id === bridgeId;
    });
    var fullUrl = "/pages/show/details/details";
    var args = "?bridgeInfo=" + JSON.stringify(bridgeInfo);
    this.navigation(fullUrl, args);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

    var page = getCurrentPages().pop();
    if (page == undefined || page == null) return;
    page.onLoad();
    wx.stopPullDownRefresh();
  },

  // 使用navigateBack
  navigation: function(pageUrl, args) {
    var cps = getCurrentPages();
    var delta = 0;
    for (var i = cps.length - 1; i >= 0; i--) {
      if ("/" + cps[i].route == pageUrl) {
        if (delta == 0) {
          return;
        }
        wx.navigateBack({
          delta: delta
        });
        return;
      }
      delta++;
    }
    wx.navigateTo({
      url: pageUrl + args,
    })
  }

})